<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>区域照片展示</title>
    <style>
      body {
        background-image: url("桥上樱花.png");
        background-size: cover; /* 使背景图像自适应页面大小 */
        background-position: center; /* 背景图像居中 */
        background-repeat: no-repeat; /* 不重复背景图像 */
        margin: 0; /* 去掉默认边距 */
        height: 100vh; /* 设置高度为视口高度 */
      }

      .carousel {
        position: relative;
        width: 800px;
        height: 500px;
        margin: 0 auto;
        overflow: hidden;
      }

      .carousel-inner {
        width: 100%;
        height: 100%;
        display: flex;
        transition: transform 0.3s ease-in-out;
      }

      .carousel-inner.no-transition {
        transition: none;
      }

      .carousel-item {
        position: relative; /* Change from absolute */
        min-width: 100%; /* Add this */
        height: 100%;
        opacity: 1; /* Remove opacity transition */
      }

      .carousel-item.active {
        opacity: 1;
      }

      .carousel-item img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }

      .carousel-control {
        position: absolute;
        top: 50%;
        transform: translateY(-50%);
        padding: 10px 20px;
        background: rgba(0, 0, 0, 0.5);
        color: white;
        border: none;
        cursor: pointer;
      }

      .carousel-prev {
        left: 10px;
      }

      .carousel-next {
        right: 10px;
      }

      .carousel-indicators {
        position: absolute;
        bottom: 20px;
        left: 50%;
        transform: translateX(-50%);
        display: flex;
        gap: 10px;
        z-index: 100;
      }

      .indicator-dot {
        width: 12px;
        height: 12px;
        border-radius: 50%;
        background-color: rgba(200, 200, 200, 0.6);
        cursor: pointer;
        transition: background-color 0.3s;
      }

      .indicator-dot.active {
        background-color: rgba(255, 255, 255, 0.8);
      }

      .arrow-button {
        position: absolute;
        top: 50%;
        transform: translateY(-50%);
        background: rgba(0, 0, 0, 0.5);
        color: white;
        border: none;
        cursor: pointer;
        padding: 15px;
        font-size: 24px;
        z-index: 100;
        border-radius: 50%;
        width: 50px;
        height: 50px;
        display: flex;
        align-items: center;
        justify-content: center;
        transition: background-color 0.3s;
      }

      .arrow-button:hover {
        background: rgba(0, 0, 0, 0.8);
      }

      .arrow-left {
        left: 2px;
      }

      .arrow-right {
        right: 2px;
      }

      /* 调整LittleBoss图片和输入框的布局 */
      .content-wrapper {
        display: flex;
        align-items: flex-start;
        width: 1000px;
        margin: 0 auto;
        position: relative;
      }

      .little-boss-image {
        width: 400px;
        height: auto;
        margin: 0;
      }

      .input-container {
        margin-left: 0px;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        height: 100%;
      }

      .input-box-a {
        width: 300px;
        min-height: 100px;
        padding: 10px;
        border: 1px solid #ccc;
        border-radius: 20px; /* 修改为圆边 */
        background-color: #f9f9f9;
        margin-bottom: 10px;
        resize: none;
        position: relative; /* 添加相对定位 */
      }

      /* 添加上下三角形 */
      .input-box-a::before,
      .input-box-a::after {
        content: ""; /* 确保有内容 */
        position: absolute;
        left: -10px; /* 调整三角形位置 */
        top: calc(50% - 10px); /* 上三角形位置 */
        border-left: 10px solid transparent;
        border-right: 10px solid transparent;
        border-top: 10px solid #f9f9f9; /* 上三角形颜色 */
      }

      .input-group-b {
        display: flex;
        gap: 10px;
      }

      .input-box-b {
        width: 240px;
        padding: 10px;
        border: 1px solid #ccc;
        border-radius: 5px;
      }

      .send-button {
        padding: 10px 15px;
        background-color: #007bff;
        color: white;
        border: none;
        border-radius: 5px;
        cursor: pointer;
      }

      .send-button:hover {
        background-color: #0056b3;
      }
    </style>
  </head>

  <body>
    <!-- 添加轮播图容器 -->
    <div class="carousel">
      <div class="carousel-inner"></div>
      <div class="carousel-indicators"></div>
      <button class="arrow-button arrow-left">←</button>
      <button class="arrow-button arrow-right">→</button>
    </div>
    <div class="content-wrapper">
      <img src="LittleBoss.png" alt="Little Boss" class="little-boss-image" />
      <div class="input-container">
        <textarea class="input-box-a" readonly></textarea>
        <div class="input-group-b">
          <input type="text" class="input-box-b" placeholder="请输入内容..." />
          <button class="send-button">发送</button>
        </div>
      </div>
    </div>
    <script>
      // 获取URL参数
      const urlParams = new URLSearchParams(window.location.search);
      const area = urlParams.get("area");

      let currentSlide = 0;
      let images = [];

      // 使用 Fetch API 调用后端接口获取图片列表
      async function loadImages() {
        try {
          // const response = await fetch(`/api/images?area=${area}`);
          const response = await fetch(
            `http://localhost:8006/api/images?area=${area}`
          );

          if (!response.ok) {
            throw new Error("Failed to fetch images");
          }
          images = await response.json();
          renderCarousel();
        } catch (error) {
          console.error("Error loading images:", error);
        }
      }

      let startX = 0;
      let isDragging = false;

      function renderCarousel() {
        const container = document.querySelector(".carousel-inner");
        container.innerHTML = "";

        // 在开头添加最后一张图片
        const lastClone = document.createElement("div");
        lastClone.className = "carousel-item";
        lastClone.innerHTML = `<img src="${
          images[images.length - 1]
        }" alt="Last Clone">`;
        container.appendChild(lastClone);

        // 添加所有实际图片
        images.forEach((image, index) => {
          const item = document.createElement("div");
          item.className = "carousel-item";
          item.innerHTML = `<img src="${image}" alt="Slide ${index + 1}">`;
          container.appendChild(item);
        });

        // 在结尾添加第一张图片
        const firstClone = document.createElement("div");
        firstClone.className = "carousel-item";
        firstClone.innerHTML = `<img src="${images[0]}" alt="First Clone">`;
        container.appendChild(firstClone);

        // 设置初始位置（因为增加了一张前置图片，所以要加1）
        currentSlide = 1;
        container.style.transform = `translateX(-${currentSlide * 100}%)`;

        const indicators = document.querySelector(".carousel-indicators");
        indicators.innerHTML = "";

        images.forEach((_, index) => {
          const dot = document.createElement("div");
          dot.className = "indicator-dot";
          if (index === 0) dot.classList.add("active");
          dot.addEventListener("click", () => showSlide(index + 1));
          indicators.appendChild(dot);
        });
      }

      function showSlide(index) {
        const container = document.querySelector(".carousel-inner");
        const totalSlides = images.length;

        // Update indicators
        const indicators = document.querySelectorAll(".indicator-dot");
        indicators.forEach((dot, i) => {
          dot.classList.toggle(
            "active",
            i === (index - 1 + totalSlides) % totalSlides
          );
        });

        currentSlide = index;

        container.style.transform = `translateX(-${currentSlide * 100}%)`;

        // 当滑动到克隆片时，等待过渡动画完成后跳转到对应的实际图片
        container.addEventListener("transitionend", function jumpToActual() {
          container.removeEventListener("transitionend", jumpToActual);

          if (currentSlide === 0) {
            // 如果到达前置克隆片，跳转到最后一张实际图片
            container.classList.add("no-transition");
            currentSlide = totalSlides;
            container.style.transform = `translateX(-${currentSlide * 100}%)`;
            container.offsetHeight; // 强制重绘
            container.classList.remove("no-transition");
          } else if (currentSlide === totalSlides + 1) {
            // 如果到达后置克隆片，跳转到第一张实际图片
            container.classList.add("no-transition");
            currentSlide = 1;
            container.style.transform = `translateX(-${currentSlide * 100}%)`;
            container.offsetHeight; // 强制重绘
            container.classList.remove("no-transition");
          }
        });
      }

      document.addEventListener("DOMContentLoaded", () => {
        const carousel = document.querySelector(".carousel");
        const leftArrow = document.querySelector(".arrow-left");
        const rightArrow = document.querySelector(".arrow-right");

        let totalDeltaX = 0;
        let isGestureActive = false;

        if (carousel) {
          // Track gesture start
          carousel.addEventListener(
            "wheel",
            (e) => {
              e.preventDefault();

              // Start tracking on first wheel event
              if (!isGestureActive && Math.abs(e.deltaX) > Math.abs(e.deltaY)) {
                isGestureActive = true;
                totalDeltaX = 0;
              }

              // Accumulate movement if gesture is active
              if (isGestureActive && Math.abs(e.deltaX) > Math.abs(e.deltaY)) {
                totalDeltaX += e.deltaX;
              }

              // Detect gesture end (when deltaX and deltaY are both 0)
              if (isGestureActive && e.deltaX === 0 && e.deltaY === 0) {
                if (Math.abs(totalDeltaX) > 50) {
                  if (totalDeltaX > 0) {
                    showSlide(currentSlide + 1);
                  } else {
                    showSlide(currentSlide - 1);
                  }
                }
                // Reset for next gesture
                isGestureActive = false;
                totalDeltaX = 0;
              }
            },
            { passive: false }
          );
        }

        // 添加箭头按钮点击事件
        leftArrow.addEventListener("click", () => {
          showSlide(currentSlide - 1);
        });

        rightArrow.addEventListener("click", () => {
          showSlide(currentSlide + 1);
        });
      });

      // 加载图片
      loadImages();

      // 添加输入框相关功能
      document.addEventListener("DOMContentLoaded", () => {
        const inputBoxB = document.querySelector(".input-box-b");
        const inputBoxA = document.querySelector(".input-box-a");
        const sendButton = document.querySelector(".send-button");

        async function sendMessage() {
          const message = inputBoxB.value.trim();
          if (!message) return;

          try {
            const response = await fetch("http://localhost:8006/ai/query", {
              method: "POST",
              headers: {
                "Content-Type": "application/json",
              },
              body: JSON.stringify({
                message: message,
                user_id: "周佳乐",
                bot_id: "default_bot",
                conversation_id: "default_conversation",
                tags: [],
              }),
            });

            // 处理流式响应
            const reader = response.body.getReader();
            const decoder = new TextDecoder("utf-8");
            let result = "";

            while (true) {
              const { done, value } = await reader.read();
              if (done) break;
              result += decoder.decode(value, { stream: true });
              inputBoxA.value = result; // 实时更新输入框内容
            }

            inputBoxB.value = ""; // 清空输入框
          } catch (error) {
            console.error("Error sending message:", error);
            inputBoxA.value = "发送消息时出错，请重试。";
          }
        }

        // 发送按钮点击事件
        sendButton.addEventListener("click", sendMessage);

        // 回车键发送
        inputBoxB.addEventListener("keypress", (e) => {
          if (e.key === "Enter") {
            e.preventDefault();
            sendMessage();
          }
        });
      });

    </script>
  </body>
</html>
